<template>
  <div>
    <!-- 页头导航 -->
    <el-page-header @back="goBack" content="添加商品"></el-page-header>
    <!-- 主体区域 -->
    <el-card>
      <!-- 提示 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addForm"
        :rules="FormRules"
        ref="addForm"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          @tab-click="tabClick"
          :before-leave="beforeTabLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="selectedCateId"
                :options="cateList"
                :props="cascaderProps"
                @change="cascaderChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyList"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="subItem"
                  v-for="(subItem, index) in item.attr_vals"
                  :key="index"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyList"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :headers="uploadProps"
              :on-preview="picturePreview"
              :on-remove="pictureRemove"
              :on-success="pictureSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="addGood()">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="previewDialog.visible" width="50%">
      <el-image :src="previewDialog.picURL" alt=""></el-image>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 当前步骤
      activeIndex: "0",
      // 添加商品信息表单数据
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_cat: "",
        goods_introduce: "",
        pics: [],
        attrs: [],
      },
      // 表单验证规则
      FormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      // 分类列表
      cateList: [],
      // 级联选择器配置
      cascaderProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      // 所选分类id数组
      selectedCateId: [],
      // 动态参数列表
      manyList: [],
      // 静态属性列表
      onlyList: [],
      // 上传图片路径
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 上传配置
      uploadProps: {
        Authorization: sessionStorage.getItem("token"),
      },
      // 图片预览对话框配置
      previewDialog: {
        visible: false,
        picURL: "",
      },
    };
  },
  methods: {
    // 监听tab标签点击
    tabClick() {
      if (this.activeIndex === "1") this.getManyList();
      else if (this.activeIndex === "2") this.getOnlyList();
    },
    // 获取所有分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cateList = res.data;
      // console.log(this.cateList)
      this.$message.success(res.meta.msg);
    },
    // 获取动态参数列表
    async getManyList() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: "many" },
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      // res.data.attr_vals=res.data.attr_vals?res.data.attr_vals.split(','):[]
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
      });
      this.manyList = res.data;
      console.log(this.manyList);
    },
    // 获取静态参数列表
    async getOnlyList() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: "only" },
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);

      this.onlyList = res.data;
      console.log(this.onlyList);
    },
    // 监听级联选择器变化
    cascaderChange() {
      if (this.selectedCateId.length !== 3) {
        this.selectedCateId = [];
        return this.$message.error("只允许选择三级分类");
      }
      // 将所选分类id转换为字符串存入addForm表单属性
      this.addForm.goods_cat = this.selectedCateId.join(",");
    },
    // 监听tab标签切换
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === "0" && this.selectedCateId.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    // 预览图片时
    picturePreview(file) {
      // console.log(file)
      this.previewDialog.picURL = file.response.data.url;
      this.previewDialog.visible = true;
      console.log(this.addForm.pics);
    },
    // 移除图片时
    pictureRemove(file) {
      const filepath = file.response.data.tmp_path;
      // 获取索引
      const index = this.addForm.pics.findIndex((x) => {
        x.pic === filepath;
      });
      // 根据索引删除
      this.addForm.pics.splice(index, 1);
    },
    // 图片上传成功时
    pictureSuccess(res) {
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);

      const picInfo = {
        pic: res.data.tmp_path,
      };
      this.addForm.pics.push(picInfo);
      this.$message.success(res.meta.msg);
    },
    // 添加新商品
    addGood() {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return this.$message.error("请输入正确的商品信息");

        this.manyList.forEach((item) => {
          const many = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          };
          this.addForm.attrs.push(many);
        });
        this.onlyList.forEach((item) => {
          const only = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addForm.attrs.push(only);
        });
        // console.log(this.addForm)

        const { data: res } = await this.$http.post("goods", this.addForm);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);

        this.$message.success(res.meta.msg);
        // 返回商品列表页面
        this.$router.push("/goods");
      });
    },
    goBack() {
      this.$router.go(-1);
    },
  },
  created() {
    this.getCateList();
  },
  computed: {
    cateId() {
      if (this.selectedCateId.length === 3) return this.selectedCateId[2];
      return null;
    },
  },
};
</script>
<style lang='less' scoped>
.el-steps {
  margin: 20px 0;
}
.el-checkbox {
  margin: 5px !important;
}
.el-page-header {
  margin-bottom: 10px;
}
.quill-editor {
  margin-bottom: 20px;
}
</style>